package com.chat;

import com.chat.mapper.UserInfoMapper;
import com.chat.mapper.UserMapper;
import com.chat.pojo.User;
import com.chat.pojo.UserInfo;
import com.chat.util.DbUtil;
import org.apache.ibatis.session.SqlSession;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.io.File;
import java.io.IOException;

public class LoginFrame {
    JFrame jFrame = new JFrame("欢迎登录QQ");
    {
        jFrame.setBounds(10, 10, 430, 550);
        jFrame.setLayout(null);
    }

    public static void main(String[] args) {
        LoginFrame login = new LoginFrame();
        login.run();
        login.after();
    }

    private void run() {
        try {
            // 创建自定义面板并设置位置与窗口大小一致
            MyPanel panel = new MyPanel();
            panel.setBounds(0, 0, jFrame.getWidth(), jFrame.getHeight());
            jFrame.add(panel);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void after() {
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    // 自定义面板类
    class MyPanel extends JPanel {
        private Image backgroundImage;
        private JTextField usernameField;
        private JTextField passwordField;
        private JLabel titleLabel;
        private JButton loginButton;
        private JButton registerButton;
        private UserMapper userMapper;

        public MyPanel() throws IOException {
            // 初始化 UserMapper
            try {
                userMapper = DbUtil.getSession().getMapper(UserMapper.class);
            } catch (Exception e) {
                throw new RuntimeException("初始化 UserMapper 失败", e);
            }

            // 加载背景图片
            backgroundImage = ImageIO.read(new File("E:\\items\\my-item\\QQ-chat\\src\\main\\java\\com\\img\\login.png"));

            // 设置布局为 null，使用绝对定位
            setLayout(null);

            // 添加标题
            titleLabel = new JLabel("欢迎登录");
            // 设置标题位置
            titleLabel.setBounds(140,40,200,150);
            titleLabel.setFont(new Font("微软雅黑",  Font.BOLD, 35));
            //设置字体颜色
            titleLabel.setForeground(new Color(20, 210, 250));

            // 创建用户名输入框
            usernameField = new JTextField();
            usernameField.setBounds(100, 180, 230, 50); // x, y, width, height
            usernameField.setBorder(new RoundBorder(40));//设置弧度
            usernameField.setOpaque(false);//文本框透明
            usernameField.setText("请输入用户名");
            usernameField.setHorizontalAlignment(JTextField.CENTER); //文本居中
            //输入框字体
            usernameField.setFont(new Font("宋体", Font.PLAIN, 15));
            //获得鼠标后提示消失
            usernameField.addFocusListener(new FocusAdapter() {
                // 点击输入框，默认字消失
                @Override
                public void focusGained(FocusEvent e) {
                    if(usernameField.getText().equals("请输入用户名")){
                        usernameField.setText("");
                    }
                }
                //  失去焦点后，如果输入框为空，则显示提示
                @Override
                public void focusLost(FocusEvent e) {
                    if(usernameField.getText().isEmpty()){
                        usernameField.setText("ice");
                    }
                }
            });

            // 创建密码输入框
            passwordField = new JPasswordField();
            passwordField.setBounds(100, 260, 230, 50);
            passwordField.setBorder(new RoundBorder(40));//设置弧度
            passwordField.setOpaque(false);//文本框透明
            passwordField.setText("041101");

            passwordField = (JPasswordField)passwordField;
            passwordField.setHorizontalAlignment(JTextField.CENTER);
            passwordField.setFont(new Font("宋体", Font.PLAIN, 15));
            passwordField.addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    if(passwordField.getText().equals("请输入密码")){
                        passwordField.setText("");
                    }
                }

                @Override
                public void focusLost(FocusEvent e) {
                    if(passwordField.getText().isEmpty()){
                        passwordField.setText("请输入密码");
                    }
                }
            });


            //登录注册
            loginButton = new JButton("登录");
            registerButton  = new JButton("注册");
            loginButton.setBounds(100, 350, 100, 50);
            registerButton.setBounds(220, 350, 100, 50);
            Font font = new Font("微软雅黑", Font.BOLD, 17);
            loginButton.setFont(font);
            registerButton.setFont(font);

            // 注册按钮点击事件
            registerButton.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e) {
                    // 创建弹窗
                    JDialog registerDialog = new JDialog(jFrame, "注册", true);
                    registerDialog.setBounds(10,10,430, 550);
                    registerDialog.setLocationRelativeTo(jFrame); // 居中显示
                    registerDialog.setLayout(null); // 使用绝对布局


                    // 设置背景面板
                    JPanel backgroundPanel = new JPanel(null) {
                        @Override
                        protected void paintComponent(Graphics g) {
                            super.paintComponent(g);
                            if (backgroundImage != null) {
                                g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
                            }
                        }
                    };


                    //标题
                    JLabel titleLabel2 = new JLabel("欢迎注册");
                    titleLabel2.setFont(new Font("微软雅黑", Font.BOLD, 35));
                    titleLabel2.setForeground(new Color(20, 210, 250));
                    titleLabel2.setBounds(120, 80, 200, 50);

                    //账号密码文本框
                    JLabel nameLable = new JLabel("账号 :");
                    JTextField nameField = new JTextField();
                    JLabel passwdLable = new JLabel("密码 :");
                    // JTextField passwdField = new JTextField();
                    JPasswordField passwdField = new JPasswordField();
                    nameLable.setFont(new Font("微软雅黑", Font.PLAIN, 20));
                    passwdLable.setFont(new Font("微软雅黑", Font.PLAIN, 20));
                    nameLable.setBounds(80, 170, 80, 50);
                    nameField.setBounds(150, 170, 200, 50);
                    passwdLable.setBounds(80, 250, 80, 50);
                    passwdField.setBounds(150, 250, 200, 50);
                    nameField.setBorder(new RoundBorder(40));
                    nameField.setOpaque(false);
                    passwdField.setBorder(new RoundBorder(40));
                    passwdField.setOpaque(false);

                    //昵称
                    // 用户昵称输入框
                    JLabel accountnameLabel = new JLabel("昵称 :");
                    JTextField accountnameField = new JTextField();
                    accountnameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
                    accountnameLabel.setBounds(80, 330, 80, 50);
                    accountnameField.setBounds(150, 330, 200, 50);
                    accountnameField.setBorder(new RoundBorder(40));
                    accountnameField.setOpaque(false);

                    // 确认按钮取消按钮
                    JButton confirmButton = new JButton("确认");
                    JButton cancelButton = new JButton("取消");
                    confirmButton.setBounds(80, 400, 100, 50);
                    cancelButton.setBounds(220, 400, 100, 50);
                    confirmButton.setFont(font);
                    cancelButton.setFont(font);


                    // 完善注册功能
                    confirmButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            String username = nameField.getText();
                            String password = passwdField.getText();
                            String accountname = accountnameField.getText();


                            System.out.println("用户名：" + username + " 密码: " + password + " 昵称: " + accountname );

                            try (SqlSession session = DbUtil.getSession()) {
                                UserMapper userMapper = session.getMapper(UserMapper.class);
                                UserInfoMapper userInfoMapper = session.getMapper(UserInfoMapper.class);
                                System.out.println("开始插入");


                                // 向 users 表插入数据
                                User user = new User();
                                user.setPassword(password);
                                user.setUsername(username);
                                System.out.println(user);

                                userMapper.addUser(user);
                                System.out.println("数据库开始插入！");
                                session.commit();
                                System.out.println("用户插入成功！");


                                // 获取刚插入用户的 user_id
                                Integer userId = userMapper.selectUserIdByUsername(username);
                                System.out.println("刚插入用户的 user_id: " + userId);


                                if (userId != null) {
                                    // 向 users_information 表插入数据
                                    UserInfo userInfo = new UserInfo(userId, username, accountname);
                                    userInfoMapper.addUserInfo(userInfo);
                                    session.commit();

                                    JOptionPane.showMessageDialog(registerDialog, "注册成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                                } else {
                                    JOptionPane.showMessageDialog(registerDialog, "注册失败：用户 ID 获取失败！", "错误", JOptionPane.ERROR_MESSAGE);
                                }

                                passwdField.setText("");
                                nameField.setText("");
                                accountnameField.setText("");


                                registerDialog.dispose();
                            } catch (Exception ex) {
                                JOptionPane.showMessageDialog(registerDialog, "注册时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                                ex.printStackTrace();
                            }
                        }
                    });

                    //取消按钮
                    cancelButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            // 关闭注册框
                            registerDialog.dispose();
                        }
                    });

                    //添加
                    backgroundPanel.add(titleLabel2);
                    backgroundPanel.add(nameLable);
                    backgroundPanel.add(nameField);
                    backgroundPanel.add(passwdLable);
                    backgroundPanel.add(passwdField);
                    backgroundPanel.add(confirmButton);
                    backgroundPanel.add(cancelButton);
                    //昵称
                    backgroundPanel.add(accountnameLabel);
                    backgroundPanel.add(accountnameField);

                    registerDialog.setContentPane(backgroundPanel);
                    registerDialog.setVisible(true);

                }
            });
            // 注册完成

            //登录
            loginButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String username = usernameField.getText();
                    String password = passwordField.getText();
                    System.out.println("用户名：" + username + "密码: " + password);

                    User user1 = new User();
                    user1.setPassword(password);
                    user1.setUsername(username);
                    System.out.println("用户：" + user1);
                    User user = userMapper.selectUser(user1);
                    System.out.println("用户：" + user);

                    if(user != null){
                        SqlSession session = DbUtil.getSession();
                        System.out.println(session);
                        UserInfoMapper userInfoMapper = session.getMapper(UserInfoMapper.class);
                        System.out.println(userInfoMapper);

                        System.out.println(" 开始登录 " );

                        UserInfo userInfo = userInfoMapper.selectUserInfoByName(username);
                        System.out.println("main: " + userInfo);

                        ChatFrame chatFrame = new ChatFrame(userInfo);
                        // ChatFrame chatFrame = new ChatFrame();
                        chatFrame.showChat();
                        jFrame.dispose();

                        usernameField.setText("");
                        passwordField.setText("");
                    }else {
                        System.out.println("账号或密码错误");
                        // 登录失败：提示账号密码错误
                        JOptionPane.showMessageDialog(jFrame, "账号或密码错误！", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });

            // 添加到面板
            add(usernameField);
            add(passwordField);
            add(titleLabel);
            add(loginButton);
            add(registerButton);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            //  绘制背景图片
            if (backgroundImage != null) {
                // 绘制背景图片
                g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
            }

        }
    }
}
